package com.wbp.cms.web.controller.admin;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.wbp.cms.client.common.domain.DictionaryDO;
import com.wbp.cms.client.common.service.DictionaryService;
import com.wbp.cms.client.customer.domain.CustomerDO;
import com.wbp.cms.client.customer.service.CustomerService;
import com.wbp.cms.client.export.BaseExportToExcel;
import com.wbp.cms.client.product.domain.ProductDO;
import com.wbp.cms.client.product.service.ProductService;
import com.wbp.cms.client.project.domain.ContractDO;
import com.wbp.cms.client.project.domain.ProjectDO;
import com.wbp.cms.client.project.domain.ProjectWorkOrderDO;
import com.wbp.cms.client.project.query.ProjectQuery;
import com.wbp.cms.client.project.query.ProjectWorkOrderQuery;
import com.wbp.cms.client.project.service.ContractService;
import com.wbp.cms.client.project.service.ProjectProfitService;
import com.wbp.cms.client.project.service.ProjectService;
import com.wbp.cms.client.project.service.ProjectWorkOrderSerivce;
import com.wbp.cms.client.result.BaseResultCode;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.user.domain.UserDO;
import com.wbp.cms.client.util.IdCardUtil;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.core.util.CommonUtil;
import com.wbp.cms.web.controller.BaseController;
import com.wbp.cms.web.util.SessionUtil;


/**
 * @Description: 
 * @Department:
 * @author andy.lhc
 * @date 2016年3月16日 下午9:05:00 
 */
@Controller("projectMgrController")
@RequestMapping("/projectmgr")
public class ProjectMgrController  extends BaseController{

  private static final Logger  logger = Logger.getLogger(ProductMgrController.class) ;
  
  @Resource
  private ProjectService  projectService ;
  
  @Resource
  private ContractService  contractService ;
  @Resource
  private ProjectProfitService projectProfitService ;
  
  @Resource
  private ProjectWorkOrderSerivce projectWorkOrderSerivce ;
  
  @Resource
  private  DictionaryService  dictionaryService ;
  
  @Resource
  private CustomerService  customerService ;
  
  @Resource
  private ProductService  productService ;
  
  /**
   * 进入页面时的方法
   * @return
   */
  @RequestMapping("/tolist")
  public ModelAndView  toList(){
    ModelAndView mv = new ModelAndView();
    
    addDictionaryValue(mv) ;
    
    mv.setViewName("admin/project/projectList"); 
    return mv ;
  }
  
  private void addDictionaryValue(ModelAndView mv){
    mv.addObject("reserveTypeList", this.dictionaryService.queryDictionary("Project", "reserveType") ) ;
    mv.addObject("statusList", this.dictionaryService.queryDictionary("Project", "status1") ) ;
    mv.addObject("typeList", this.dictionaryService.queryDictionary("Project", "type") ) ;
  }
  
  /**
   * to 新增预约项目页面
   * @return
   */
  @RequestMapping("/toadd")
  public ModelAndView  toAddProject(@RequestParam(value="customerId",required=true,defaultValue="0") Long customerId){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/project/projectAdd"); 
     
     if(customerId == 0)
       mv.setViewName("error/500");
     
     CustomerDO  customer = this.customerService.queryCustomerById(customerId) ;
     if(customer !=null)
       mv.addObject("customer", customer) ;
     
     addDictionaryValue(mv) ;
     
     return  mv ;
  }
  
  /**
   * 新增预约项目
   * @param request
   * @return
   */
  @RequestMapping(value="/doadd", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public  String   doAddProject(HttpServletRequest request  ){

    try{
         ProjectDO  projectDO = getRequestObject(request,ProjectDO.class) ;
        if(projectDO == null )
           return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        if(projectDO.getProductId() == null || projectDO.getProductId() <=0)
           return JsonUtils.toJson(Result.buildError("预约项目名称不能为空")) ;
        if(StringUtils.isBlank(projectDO.getProjectName()))
           return JsonUtils.toJson(Result.buildError("预约项目名称不能为空")) ;
        if(projectDO.getCustomerId() == null || projectDO.getCustomerId() <=0)
          return JsonUtils.toJson(Result.buildError("客户姓名不能为空")) ;
        if(StringUtils.isBlank(projectDO.getCustomerName()))
          return JsonUtils.toJson(Result.buildError("客户姓名不能为空")) ;
        if(StringUtils.isBlank(projectDO.getIdCard()))
          return JsonUtils.toJson(Result.buildError("身份证号码不能为空")) ;
        if(!IdCardUtil.verify(projectDO.getIdCard()))
          return JsonUtils.toJson(Result.buildError("身份证号码不合法")) ;
        if(StringUtils.isBlank(projectDO.getMobileNumber()))
          return JsonUtils.toJson(Result.buildError("手机号码不能为空")) ;
        if(!CommonUtil.isMobile(projectDO.getMobileNumber()))
          return JsonUtils.toJson(Result.buildError("手机号码不合法")) ; 
        if(StringUtils.isBlank(projectDO.getPaymoneyDate()))
          return JsonUtils.toJson(Result.buildError("预约打款日期不能为空")) ;
        
        UserDO  user = SessionUtil.getCurrentUser(request.getSession()) ;
        if(user == null){
            return JsonUtils.toJson(Result.buildError("请重新登录")) ;
        }
        projectDO.setUserId(user.getId());
        projectDO.setUserName(user.getUserName());
        projectDO.setStatus(1); // 合同已申请
        
        Result<Long> result = this.projectService.addProject(projectDO) ;
           
        return  JsonUtils.toJson(result) ;
    }catch(Throwable  t){
      logger.error(BaseResultCode.PROJECT_ADD_PROJECT_ERROR.getErrMsg(), t);
      return JsonUtils.toJson(Result.buildError(t.getMessage()));
    }
    
   
  }
  
  
  
  /**
   * to  修改页面 
   * @param productId
   * @return
   */
  @RequestMapping("/toedit")
  public ModelAndView  toEditProduct(@RequestParam(value="projectId",required=true,defaultValue="0") Long projectId){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/project/projectEdit"); 
     
     Result<ProjectDO>  result = this.projectService.loadProject(projectId) ;
     if(result.isSuccess()  && result.getData() != null)
        mv.addObject("project",  result.getData()) ;
      
     addDictionaryValue(mv) ;
     
     if(result.isSuccess()  && result.getData() != null && result.getData().getStatus() > 0 ){
         if(result.getData().getReserveType() == 1) // 1:客户自签,
            mv.addObject("statusList", this.dictionaryService.queryChildDictionary("Project", "status1",result.getData().getStatus()) ) ;
         else if( result.getData().getReserveType() == 2 ) // 2:上门面签 
           mv.addObject("statusList", this.dictionaryService.queryChildDictionary("Project", "status2",result.getData().getStatus()) ) ;
     }
     
     return  mv ;
  }
  /**
   * 保存修改
   * @param request
   * @return
   */
  @RequestMapping(value="/doedit", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public String  doEditProject(HttpServletRequest request    ){
    try{

        ProjectDO  projectDO = getRequestObject(request,ProjectDO.class) ;
        if(projectDO == null )
            return JsonUtils.toJson(Result.buildError("参数不合法")) ;
       if(projectDO.getId() == null || projectDO.getId() <=0)
            return JsonUtils.toJson(Result.buildError("请重新刷新页面再修改预约项目信息")) ;
       
       if(projectDO.getStatus()<=0 )
         return JsonUtils.toJson(Result.buildError("预约项目状态:"+projectDO.getStatus()+" 应>0")) ;
        Result<Boolean>  result =this.projectService.modifyProject(projectDO) ;
        
        return  JsonUtils.toJson(result ,true) ;
    }catch(Throwable e){
      logger.error(BaseResultCode.PROJECT_MODIFY_PROJECT_ERROR.getErrMsg(), e);
      return JsonUtils.toJson(Result.buildError(e.getMessage()));
    }
  }
  
  /**
   * 查询
   * @param request
   * @param projectName
   * @param userName
   * @param mobileNumber
   * @param reserveType
   * @param type
   * @param start
   * @param pageSize
   * @return
   */
  @RequestMapping(value="/query", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public String doQuery(HttpServletRequest request,@RequestParam(value = "projectName", 
      required = false, defaultValue = "") String projectName, @RequestParam(value = "customerName",
      required = false, defaultValue = "") String customerName,@RequestParam(value = "mobileNumber",
      required = false, defaultValue = "") String mobileNumber,@RequestParam(value = "userName",
          required = false, defaultValue = "") String userName,@RequestParam(value = "reserveType",
      required = false, defaultValue = "0") int reserveType ,@RequestParam(value = "type",
      required = false, defaultValue = "0") int type ,  @RequestParam(value = "status",
          required = false, defaultValue = "0") int status,@RequestParam(value="startTime",
          required=false,defaultValue="") String  startTime ,@RequestParam(value="endTime",
              required=false,defaultValue="") String  endTime ,@RequestParam(value = "start",
      required = false, defaultValue = "1") int start,@RequestParam(value = "length",
      required = false, defaultValue = "50") int pageSize) {

    Map<String,String> maps = this.getParameters(request) ;
    
    ProjectQuery  query =new ProjectQuery();
    // productQuery.setPageNo(pageNo);
    query.setStart(start);
    query.setPageSize(pageSize);
    if(StringUtils.isNotEmpty(projectName))
      query.setProjectName(projectName);
    if(StringUtils.isNotEmpty(customerName))
      query.setCustomerName(customerName);
    if(StringUtils.isNotEmpty(mobileNumber))
      query.setMobileNumber(mobileNumber);
    if(StringUtils.isNotEmpty(userName))
      query.setUserName(userName);
    if(reserveType >0)
      query.setReserveType(reserveType); 
    if(type >0)
      query.setType(type) ; 
    if(status > 0 )
      query.setStatus(status);
    
    if(StringUtils.isNotBlank(startTime))
       query.setStartTime(startTime); 
    if(StringUtils.isNotBlank(endTime))
       query.setEndTime(endTime);
    
    UserDO  user = SessionUtil.getCurrentUser(request.getSession() ) ;
    if(!this.isSuperUser(user.getUserName())){
       query.setOrganizationId(user.getOrganizationId());
    }
    
    Result<List<ProjectDO>> result = this.projectService.queryProject(query) ;
    setQueryValue(result) ;
    return new Gson().toJson(getDataTableMapData(result,maps.get(DT_KEY_DRAW) )) ;
     
  } 
  
  private void setQueryValue(Result<List<ProjectDO>> result ){
    if(result.isSuccess() && result.getData() !=null && !result.getData().isEmpty() ){
      for(ProjectDO p: result.getData()){
          p.setReserveTypeDesc( getDictionaryDesc("Project", "reserveType", p.getReserveType() ) );
          p.setTypeDesc(getDictionaryDesc("Project", "type", p.getType() ));
          if(p.getType() == 1) // 个人 
            p.setStatusDesc(getDictionaryDesc("Project", "status1", p.getStatus()) );
          else if(p.getType() == 2) // 机构
            p.setStatusDesc(getDictionaryDesc("Project", "status2", p.getStatus()) );
          else
            p.setStatusDesc("");
      }
   }
  }
  
  private String  getDictionaryDesc(String tableName,String attributeName, int value){
    DictionaryDO  dictionary = this.dictionaryService.queryDictionary(tableName, attributeName,  value ) ;
    if(dictionary == null || dictionary.getDescription()==null)
       return "" ;
    return dictionary.getDescription() ;
  }
  
  
  /**
   * 导出
   * @param request
   * @param projectName
   * @param userName
   * @param mobileNumber
   * @param reserveType
   * @param type
   * @param start
   * @param pageSize
   * @param response
   */
  @RequestMapping(value="/export", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public void doExport(HttpServletRequest request,@RequestParam(value = "projectName",
      required = false, defaultValue = "") String projectName, @RequestParam(value = "customerName",
          required = false, defaultValue = "") String customerName,@RequestParam(value = "mobileNumber",
          required = false, defaultValue = "") String mobileNumber,@RequestParam(value = "userName",
              required = false, defaultValue = "") String userName,@RequestParam(value = "reserveType",
      required = false, defaultValue = "0") int reserveType ,@RequestParam(value = "type",
      required = false, defaultValue = "0") int type , @RequestParam(value = "status",
          required = false, defaultValue = "0") int status,@RequestParam(value="startTime",
          required=false,defaultValue="") String  startTime ,@RequestParam(value="endTime",
              required=false,defaultValue="") String  endTime,@RequestParam(value = "start",
      required = false, defaultValue = "1") int start,@RequestParam(value = "length",
      required = false, defaultValue = "50") int pageSize,HttpServletResponse response) {
  
    ProjectQuery  query =new ProjectQuery();
    query.setStart(start);
    pageSize = 1000 ; // 只导前1000条，导出太多，影响情能 
    
    query.setPageSize(pageSize);
    if(StringUtils.isNotEmpty(projectName))
      query.setProjectName(projectName);
    if(StringUtils.isNotEmpty(customerName))
      query.setCustomerName(customerName);
    if(StringUtils.isNotEmpty(mobileNumber))
      query.setMobileNumber(mobileNumber);
    if(StringUtils.isNotEmpty(userName))
      query.setUserName(userName);
    if(reserveType >0)
      query.setReserveType(reserveType); 
    if(type >0)
      query.setType(type) ; 
    if(status > 0 )
      query.setStatus(status);
    if(StringUtils.isNotBlank(startTime))
      query.setStartTime(startTime); 
  if(StringUtils.isNotBlank(endTime))
     query.setEndTime(endTime);
    Result<List<ProjectDO>> result = this.projectService.queryProject(query) ;
    List<ProjectDO>  pl = result.getData() ;
    BaseExportToExcel  export = new BaseExportToExcel(headers,headerAttributes) ;
    if(pl == null || pl.isEmpty() ){
        List<Map<String, Object>> list = Lists.newArrayList() ;
        export.setDataList(list ); 
    }else{
        setQueryValue(result) ;
        // 格式化，字典值，时间值，先格式化后再转成json .
        String  jsonStr = JsonUtils.toJson(pl) ;
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> dataList=  JsonUtils.toObject(jsonStr, List.class) ;
        export.setDataList(dataList); 
    }
    
    try {
         setExportContentType(response) ;
        export.exportToExcel(response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    } 
     
  } 
  
  private final String[] headers = new String[]{"项目名称","预约人姓名","预约人身份证号码 ","预约人手机号码","预约类型","类型","预计打款时间","说明","预约金额,单位万","推荐人姓名","当前状态","受益人","汇款银行","银行尾号","预期收益","成立日期","清算日期","合同快递单号-客户","合同快递单号-公司","公司全名称","企业法人" };
  private final String[] headerAttributes = new String[]{"projectName","customerName","idCard","mobileNumber","reserveTypeDesc","typeDesc","paymoneyDate","instruction","preAmount","userName","statusDesc","benefitPerson","txtBank","txtAccount","expectedProfit","createDate","endDate","logisticsNumberCustomer","logisticsNumberCompany","companyName","legalPerson"};
  
  
  /**
   * 查询预约项目流程记录
   * @param request
   * @param projectName
   * @param userName
   * @param mobileNumber
   * @param reserveType
   * @param type
   * @param start
   * @param pageSize
   * @return
   */
  @RequestMapping(value="/querypw", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public String doQueryProjectWorkOrder(HttpServletRequest request,@RequestParam(value = "projectId",
      required = false, defaultValue = "0") Long projectId ,@RequestParam(value = "start",
      required = false, defaultValue = "1") int start,@RequestParam(value = "length",
      required = false, defaultValue = "50") int pageSize) {
    
    Map<String,String> maps = this.getParameters(request) ; 
    
    Result<ProjectDO> r = this.projectService.loadProject(projectId);
  //  if(r.isFailed())
  //    return new Gson().toJson(getDataTableMapData(pr,maps.get(DT_KEY_DRAW) )) ;
    
    ProjectWorkOrderQuery pwq = new ProjectWorkOrderQuery();
    pwq.setProjectId(projectId);  
    pwq.setStart(start);
    pwq.setPageSize(pageSize);
    
    Result<List<ProjectWorkOrderDO>>  pr = projectWorkOrderSerivce.queryProjectWorkOrderByProject(projectId) ;
    if(r.isSuccess() && r.getData() !=null && pr.isSuccess() && pr.getData() !=null && !pr.getData().isEmpty() ){
        for(ProjectWorkOrderDO p : pr.getData()){
           p.setProjectName(r.getData().getProjectName() );
        }
    }
    return new Gson().toJson(getDataTableMapData(pr,maps.get(DT_KEY_DRAW) )) ;
  }
  
  /**
   * 查看合同信息
   * @param request
   * @param projectId
   * @return
   */
  @RequestMapping(value="/showcontract", produces = "application/json;charset=UTF-8")
  @ResponseBody
  public String doShowcontract(HttpServletRequest request,@RequestParam(value = "projectId",
      required = false, defaultValue = "0") Long projectId){
    if(projectId==null || projectId<=0)
       return JsonUtils.toJson(Result.buildError("projectId不能为空,应>0"));
    
    ContractDO c = contractService.loadContractByProject(projectId) ;
    if(c == null)
        return JsonUtils.toJson("根据projectId:"+projectId+",没有查到对应的合同信息");
    
    return JsonUtils.toJson(Result.buildSuccess(c) );
  }
  
  
  
}
